package com.burgeon.backend.service.Impl;


import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.TemplateMapper;
import com.burgeon.backend.mappers.UserMapper;
import com.burgeon.backend.service.CodeService;
import com.burgeon.backend.service.CouponService;
import com.burgeon.backend.service.MessageTemplateService;
import com.burgeon.backend.service.ex.ErrorDataException;
import com.burgeon.backend.service.ex.PhoneException;
import com.burgeon.backend.service.ex.SendCodeException;
import com.burgeon.backend.verification.GetMessageCode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

@Service
public class CodeServiceImpl implements CodeService {
    private final static Log logger = LogFactory.getLog(CodeService.class);

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private CouponService couponService;
    @Autowired
    private MessageTemplateService messageTemplateService;

    private final static String PHONE_PATTERN = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17([0,1,6,7,]))|(18[0-2,5-9]))\\d{8}$";

    @Override
    public void verificationCode(String phone, HttpSession session) throws PhoneException, SendCodeException {
        boolean isPhone = Pattern.compile(PHONE_PATTERN).matcher(phone).matches();

        if (!isPhone) {
            throw new PhoneException("号码格式错误");
        }

        session.setAttribute("phone", phone);
        if (null == session.getAttribute("restrict")) {
            //发送验证码 储存 限定时间
            String rod = (int) ((Math.random() * 9 + 1) * 100000) + "";//创建验证码
            try {

                GetMessageCode.getCode(phone, rod);
                System.err.println("rod=" + rod);
                session.setAttribute("verification", rod);
                session.setAttribute("restrict", "off");//发送频繁限制
                long date = new Date().getTime();
                session.setAttribute("codeDate", date);
                //5分钟后删除验证码
                final Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Long fdate = (Long) session.getAttribute("codeDate");
                        Long ndate = new Date().getTime();
                        if (ndate - fdate >= 300000) {
                            session.removeAttribute("verification");
                            System.err.println("5分钟删除");
                        }
                        timer.cancel();
                    }
                }, 5 * 60 * 1000);

                //1分钟后允许继续发送
                final Timer timerCode = new Timer();
                timerCode.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        session.removeAttribute("restrict");
                        System.err.println("1分钟解除限制");
                        timerCode.cancel();
                    }
                }, 60 * 1000);

            } catch (Exception e) {

                logger.error(e.getMessage() + "验证码发送错误，请稍后再试");
                throw new SendCodeException("验证码发送错误，请稍后再试");
            }
        } else {
            //发送频繁
            logger.error("验证码发送错误，请稍后再试");
            throw new SendCodeException("验证码发送频繁，请稍后再试");
        }
    }

    @Override
    public void Judge(String phone, String code, HttpSession session) throws PhoneException, SendCodeException, ErrorDataException {

        String token = session.getAttribute("token").toString();
        //String openid = session.getAttribute("openid").toString();
        //String account = accountMapper.GetAccountForToken(token);
       /* if (null == code) { 开启验证码
            throw new SendCodeExceptionApp("验证码不能为空");
        }
        if (!phone.equals(session.getAttribute("phone"))) {
            throw new SendCodeExceptionApp("验证码输入错误");
        }
        if (null == session.getAttribute("verification")) {
            throw new SendCodeExceptionApp("验证码输入超时");
        }
        if (!code.equals(session.getAttribute("verification"))) {
            throw new SendCodeExceptionApp("验证码输入错误");
        }*/

        /*Info info = GetInfo(token);
        UserExist userExist = new UserExist(info.getUrl(), info.getAccount(), info.getPassword());
        User user;
        try {
            user = userExist.getData(phone);
        } catch (Exception e) {
            throw new PhoneExceptionApp();
        }
        //写入openid
        UserReadOpenid userReadOpenid = new UserReadOpenid(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            userReadOpenid.getData(user.getId(), openid);
        } catch (Exception e) {
            logger.error(e.getMessage() + "数据错误");
            throw new ErrorDataExceptionApp("数据错误");
        }

        user.setToken(token);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(now);
        user.setCreateTime(dateString);
        user.setPhone(phone);
        user.setOpenid(openid);
        user.setAccount(account);

        userMapper.Register(user);
        User finalUser = user;

        Thread thread = new Thread(() -> {
            logger.error(finalUser);

            //发券  发积分  发消息
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignored) {
            }
            TemplateSwitch templateSwitch = templateMapper.FindTemplateSwitch(account);
            if ("Y".equals(templateSwitch.getSwitch1())) {
                //发券
                logger.error(templateSwitch);
                couponService.addCoupon(templateSwitch.getValue1(),phone,account);
            }

            if ("Y".equals(templateSwitch.getSwitch2())){
                CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                try {
                    Thread.sleep(1000);
                    createIntegral.getData(phone,"-"+templateSwitch.getValue2());
                    messageTemplateService.SendMessageForNewUser(token,openid,phone,templateSwitch.getValue2(),finalUser.getName());
                } catch (Exception e) {
                     logger.error("新会员积分调整错误"+ Arrays.toString(e.getStackTrace())+e.getMessage());
                }
            }
        });
        thread.start();*/

    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }

}
